package cn.wygandwdn.core.loadbalancer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description:    轮询负载均衡策略
 * @author: WYG
 * @time: 2021/10/25 21:06
 */

public class RoundRobinLoadBalancer implements LoadBalancer {

    private static final Logger log = LoggerFactory.getLogger(RoundRobinLoadBalancer.class);

    private AtomicInteger atomicInteger = new AtomicInteger(0);
    public final Integer getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        log.debug("view counts next value is:\t" + next);
        return next;
    }

    @Override
    public <T> T select(List<T> instances) {
        int index = getAndIncrement() % instances.size();
        return instances.get(index);
    }
}
